//
// Created by HP on 2025/11/17.
//

#include "Browse.h"
#include <iostream>

Browse::Browse() : Model("browses") {
    setTableDefault("userId", "INT NOT NULL");
    setTableDefault("ticketId", "INT NOT NULL");
    setTableDefault("browseTime", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
    setTableDefault("createdAt", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
}

void Browse::bind(const std::string& key, const std::string& value) {
    if (!TableCols.count(key)) {
        std::cerr << "Error: Invalid key for browse bind" << std::endl;
        return;
    }
    if (TableCols[key].find("UNIQUE") == std::string::npos && key != "id") {
        std::cerr << "Error: Key is not unique for browse bind" << std::endl;
        return;
    }

    std::string selectSql = "SELECT * FROM " + TableName + " WHERE " + key + " = '" + Model::escapeSqlLiteral(value) + "';";
    std::vector<std::map<std::string, std::string>> result = DBConnector::getInstance()->query(selectSql);

    if (result.empty()) {
        std::cerr << "bind failed: SQL execution error or no result. SQL: " << selectSql << std::endl;
        return;
    }

    std::cout << "bind success. Table: " << TableName << std::endl;

    if (result.size() > 1) {
        std::cerr << "Error: Multiple browses found with the same " << key << std::endl;
        return;
    } else if (result.size() == 1) {
        this->id = result[0]["id"];
        this->userId = result[0]["userId"];
        this->ticketId = result[0]["ticketId"];
        this->browseTime = result[0]["browseTime"];
        this->createdAt = result[0]["createdAt"];
    }
}

bool Browse::save() {
    std::string createBrowseSql = "INSERT INTO " + TableName + " (userId, ticketId";
    std::string valuesSql = " VALUES (" + userId + ", " + ticketId;
    
    if (!browseTime.empty()) {
        createBrowseSql += ", browseTime";
        valuesSql += ", '" + Model::escapeSqlLiteral(browseTime) + "'";
    }
    
    createBrowseSql += ")";
    valuesSql += ");";
    
    std::string fullSql = createBrowseSql + valuesSql;
    int executeCode = DBConnector::getInstance()->execute(fullSql);
    if (executeCode == -1) {
        std::cerr << "create browse failed: SQL execution error. SQL: " << fullSql << std::endl;
        return false;
    } else {
        std::cout << "create browse success. Table: " << TableName << std::endl;
        return true;
    }
}
